package com.elinkway.infinitemovies.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.elinkway.infinitemovies.adapter.RecyclerListAdapter;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.tips.DefaultTipsHelper;
import com.elinkway.infinitemovies.tips.TipsHelper;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.widget.OverScrollLayout;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoBaseBean;
import com.recyclerlayout.refresh.RecyclerRefreshLayout;

/**
 * Created by zhaopeipei on 2017/3/6.
 */
public abstract class BaseRecyclerFragment extends Fragment {

    public static final String TAG = "BaseListFragment";

    private TipsHelper mTipsHelper;

    private View mRootView;

    protected RecyclerView mRecyclerView;
    protected OverScrollLayout mOverScrollView;

    private RecyclerRefreshLayout mRecyclerRefreshLayout;

    private RecyclerListAdapter mOriginAdapter;


    public ImageView mLayerView; // 右下角浮层

    public final LoadMoreEventDetector mLoadMoreEventDetector = new LoadMoreEventDetector();

    public final RefreshEventDetector mRefreshEventDetector = new RefreshEventDetector();

    private boolean mIsLoading;

    // 影视大全为不可加载，超级视频为可加载
    private boolean mAllowLoading = true;

    private boolean mAllowPullToRefresh = true;

    private PullListener mPullListener;

    public PublicLoadLayout root;

    private long lastRequestMoreTime;

    private long currentRequestMoreTime;

    public boolean lastRequestMoreSuccessed = true;

    protected View mBaseRllayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        root = UIs.createPage(getActivity(), R.layout.base_refresh_recycler_list_layout);
        root.loading(false);
        LogUtils.i("onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LogUtils.i("onCreateView");
        initView(root);
        initRecyclerRefreshLayout(root);
        mTipsHelper = createTipsHelper();
        return root;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        LogUtils.i("onViewCreated");
    }

    public void setPullListener(PullListener listener) {
        mPullListener = listener;
    }

    public void setAdapter(RecyclerListAdapter recyclerListAdapter) {
        mOriginAdapter = recyclerListAdapter;
        mRecyclerView.setAdapter(mOriginAdapter);
    }

    public void setLayoutManager(RecyclerView.LayoutManager layoutManager) {
        mRecyclerView.setLayoutManager(layoutManager);
    }

    protected TipsHelper createTipsHelper() {
        return new DefaultTipsHelper(this);
    }

    public void refresh() {
        if (isFirstPage()) {
            mTipsHelper.showLoading(true);
        } else {
            mRecyclerRefreshLayout.setRefreshing(true);
        }
        requestRefresh();
    }

    public void resetLoading() {
        mIsLoading = false;
    }

    public boolean isFirstPage() {
        return mOriginAdapter.getItemCount() <= 0;
    }

    public void loadMore() {

    }

    public boolean hasLoadMore() {
        return false;
    }

    public boolean isRefreshing() {
        return false;
    }

    private void initView(View view) {
        LogUtils.i("initRecyclerView");
        mBaseRllayout = view.findViewById(R.id.base_rl_layout);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        mRecyclerView.getItemAnimator().setChangeDuration(0);
        mOverScrollView = (OverScrollLayout) view.findViewById(R.id.over_scroll_view);
        mOverScrollView.setOverScrollEnable(false);
        mLayerView = (ImageView) view.findViewById(R.id.home_layer_ad);
        addOnScrollListener();
    }

    public void addOnScrollListener() {
        if (mRecyclerView != null && mLoadMoreEventDetector != null) {
            mRecyclerView.addOnScrollListener(mLoadMoreEventDetector);
        }

    }

    public class LoadMoreEventDetector extends RecyclerView.OnScrollListener {
        @Override
        public void onScrolled(RecyclerView view, int dx, int dy) {
            RecyclerView.LayoutManager manager = view.getLayoutManager();
            if (manager.getChildCount() > 0) {
                int count = manager.getItemCount();
                int last = ((RecyclerView.LayoutParams) manager
                        .getChildAt(manager.getChildCount() - 1).getLayoutParams()).getViewAdapterPosition();
                if (last >= count - 2 && !mIsLoading && mPullListener != null && mAllowLoading && dy >= 0) {
                    currentRequestMoreTime = System.currentTimeMillis();
                    if ((currentRequestMoreTime - lastRequestMoreTime > 5000) || lastRequestMoreSuccessed) {
                        mIsLoading = true;
                        requestMore();
                        lastRequestMoreTime = currentRequestMoreTime;
                    }
                }
            }
        }
    }

    private void requestMore() {
        mPullListener.requestMore();
    }

    private void initRecyclerRefreshLayout(View view) {
        LogUtils.i("initRecyclerRefreshLayout");
        mRecyclerRefreshLayout = (RecyclerRefreshLayout) view.findViewById(R.id.refresh_layout);
        if (mRecyclerRefreshLayout == null) {
            return;
        }
        if (allowPullToRefresh()) {
            mRecyclerRefreshLayout.setNestedScrollingEnabled(true);
            mRecyclerRefreshLayout.setOnRefreshListener(mRefreshEventDetector);
        } else {
            mRecyclerRefreshLayout.setEnabled(false);
        }
    }

    // 默认为true
    public boolean allowPullToRefresh() {
        return mAllowPullToRefresh;
    }

    public void setPullToRefreshEnable(boolean allowToRefresh) {
        mAllowPullToRefresh = allowToRefresh;
    }

    public void setAllowloading(boolean allowloading) {
        mAllowLoading = allowloading;
    }


    public abstract class PullListener {
        public void requestRefresh() {
            if (hasMore()) {
                LogUtils.i("requestRefresh");
                mTipsHelper.showHasMore();
            }
        }

        public void requestMore() {
            // 请求接口
        }

        public void requestFailure() {
            requestComplete();
            root.error(false, false);
            root.setmRefreshData(new PublicLoadLayout.RefreshData() {
                @Override
                public void refreshData() {
                    root.loading(false);
                    requestRefresh();
                }
            });
        }

        public void requestComplete() {
            LogUtils.i("requestMore requestComplete" + mIsLoading);
            mIsLoading = false;
            root.finish();
            if (mRecyclerRefreshLayout != null) {
                mRecyclerRefreshLayout.setRefreshing(false);
            }
            mTipsHelper.hideError();
            mTipsHelper.hideEmpty();
            mTipsHelper.hideLoading();
        }

        protected boolean hasMore() {
            return true;
        }
    }

    public abstract class BasePullRequestListener<T extends LVideoBaseBean> implements RequestResultListener<T> {
        public boolean onRequestFailed() {
            if (mPullListener != null) {
                mPullListener.requestFailure();
            }
            lastRequestMoreSuccessed = false;
            return false;
        }

        public void onRequestSuccess(int updateId, T result) {
            if (mPullListener != null) {
                mPullListener.requestComplete();
            }
            lastRequestMoreSuccessed = true;
        }

        public void onPreRequest() {

        }
    }

    public class RefreshEventDetector implements RecyclerRefreshLayout.OnRefreshListener {
        @Override
        public void onRefresh() {
            requestRefresh();
        }
    }

    public void requestRefresh() {
        if (mPullListener != null && !mIsLoading) {
            mIsLoading = true;
            mPullListener.requestRefresh();
        }
    }

    public RecyclerRefreshLayout getRecyclerRefreshLayout() {
        return mRecyclerRefreshLayout;
    }

    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    @Override
    public void onDestroyView() {
        mRecyclerView.removeOnScrollListener(mLoadMoreEventDetector);
        super.onDestroyView();
    }

}
